package cn.edu.zut.soft.student.service.login.impl;

import cn.edu.zut.soft.student.dao.StudentMapper;
import cn.edu.zut.soft.student.dao.TeacherMapper;
import cn.edu.zut.soft.student.model.Student;
import cn.edu.zut.soft.student.model.Teacher;
import cn.edu.zut.soft.student.model.enums.Role;
import cn.edu.zut.soft.student.service.login.LoginBo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * @Author ChrisPhantom
 * @CreatDate 2021/02/14 18:13
 */


@Service
public class LoginBoImpl implements LoginBo {
    @Autowired
    private HttpSession session;

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private TeacherMapper teacherMapper;


    @Override
    public String handleLogin(String username, String password) {
        if (username.equals(Role.admin_name) && password.equals(Role.admin.getPassword())) {
            session.setAttribute("LoginUser", username);
            session.setAttribute("classify", "admin");
            return "/admin";
        } else {
            Student student = studentMapper.selectByPrimaryKey(username);
            Teacher teacher = teacherMapper.selectByPrimaryKey(username);
            if (student == null && teacher == null) {
                return "/login";
            }
            String sp = "";
            String tp = "";
            if (student != null) {
                sp = student.getPassword();
            }
            if (teacher != null) {
                tp = teacher.getPassword();
            }
            if (password.equals(sp)) {
                session.setAttribute("LoginUser", username);
                session.setAttribute("classify", "student");
                session.setAttribute("name", student.getStudentname());
                return "/student";
            } else if (password.equals(tp)) {
                session.setAttribute("LoginUser", username);
                session.setAttribute("classify", "teacher");
                session.setAttribute("name", teacher.getTeachername());
                return "/teacher";
            } else {
                return "/login";
            }
        }
    }

    @Override
    public String logout() {
        session.removeAttribute("LoginUser");
        session.removeAttribute("classify");
        session.removeAttribute("name");
        return "/index";
    }
}
